package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * Exception handler
 * @author 武帅丞
 * @date 2024/9/11
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(ReggieException.class)
    public ServerResultVO<String> exceptionHandler(ReggieException exception) {
        log.error(exception.getMessage());
        return ServerResultVO.error(exception.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ServerResultVO<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());

        if (StringUtils.startsWith(exception.getMessage(), "Duplicate entry")) {
            String content = exception.getMessage().split(" ")[2];
            return ServerResultVO.error(content + "already exists");
        }
        return ServerResultVO.error("UKE: field value conflict");
    }
}
